import axios from "axios"

let mode = 0;
const playMode = {
    sequence: 0,  //顺序播放
    loop: 1,  //单曲循环
    random: 2,  //随机播放
}
const song = {
    namespaced: true,
    actions: {
        setSongList(content, value) {
            axios
                .get("http://localhost:3000/cloudsearch", {
                    params: {
                        keywords: value.keywords,
                        limit: 10,
                        offset: value.pageNum * 10
                    },
                })
                .then((response) => {
                    if (response.data.result.songCount === 0) {
                        alert("曲库未收录");
                    } else {
                        // console.log("歌曲查找成功", response);
                        content.commit('SETSONGLIST', response.data.result.songs)
                    }
                })
                .catch((error) => {
                    console.warn(error);
                });
        },
        setSongListMean(content, value) {
            axios
                .get("http://localhost:3000/cloudsearch", {
                    params: {
                        keywords: value.keywords,
                        limit: 10,
                        offset: value.pageNum * 10,
                        type:1000
                    },
                })
                .then((response) => {
                    if (response.data.result.songCount === 0) {
                        alert("曲库未收录");
                    } else {
                        console.log("歌单查找成功", response);
                        content.commit('SETSONGLISTMEAN', response.data.result.playlists)
                    }
                })
                .catch((error) => {
                    console.warn(error);
                });
        },
        getSongLyric(content, value) {
            axios
                .get('http://localhost:3000/lyric', {
                    params: {
                        id: value.id
                    }
                })
                .then((response) => {
                    // console.log(response.data.lrc.lyric)
                    content.commit('GETSONGLYRIC', response.data.lrc.lyric)
                })
                .catch((error) => {
                    console.warn(error)
                })
        }
    },
    mutations: {
        SETSONGLIST(state, value) {
            state.songList = value
            //将查找出的歌曲列表添加到新歌单而不是赋值去取代
            state.sequencePlayList.push(...value)
            //对歌单进行过滤然后赋值给新歌单
            let obj = {}
            let arr = state.sequencePlayList.reduce((item, next) => {
                obj[next.id] ? "" : obj[next.id] = true && item.push(next);
                return item;
            }, [])
            state.sequencePlayListJust = arr
        },
        SETSONGLISTMEAN(state, value) {
            state.songListMean = value
        },
        GETSONGLYRIC(state, value) {
            let oLRC = {
                offset: 0, //时间补偿值，单位毫秒，用于调整歌词整体位置
                ms: [] //歌词数组{t:时间,c:歌词}
            };
            function createLrcObj(lrc) {
                if (lrc.length == 0) return;
                let lrcs = lrc.split('\n');//用回车拆分成数组
                for (let i in lrcs) {//遍历歌词数组
                    lrcs[i] = lrcs[i].replace(/(^\s*)|(\s*$)/g, ""); //去除前后空格
                    let t = lrcs[i].substring(lrcs[i].indexOf("[") + 1, lrcs[i].indexOf("]"));//取[]间的内容
                    let s = t.split(":");//分离:前后文字
                    if (isNaN(parseInt(s[0]))) { //不是数值
                        for (let i in oLRC) {
                            if (i != "ms" && i == s[0].toLowerCase()) {
                                oLRC[i] = s[1];
                            }
                        }
                    } else { //是数值
                        let arr = lrcs[i].match(/\[(\d+:.+?)\]/g);//提取时间字段，可能有多个
                        let start = 0;
                        for (let k in arr) {
                            start += arr[k].length; //计算歌词位置
                        }
                        let content = lrcs[i].substring(start);//获取歌词内容
                        for (let k in arr) {
                            let t = arr[k].substring(1, arr[k].length - 1);//取[]间的内容
                            let s = t.split(":");//分离:前后文字
                            oLRC.ms.push({//对象{t:时间,c:歌词}加入ms数组
                                t: (parseFloat(s[0]) * 60 + parseFloat(s[1])).toFixed(3),
                                c: content
                            });
                        }
                    }
                }
                oLRC.ms.sort(function (a, b) {//按时间顺序排序
                    return a.t - b.t;
                });
                // for (var i in oLRC) { //查看解析结果
                //     console.log(i, ":", oLRC[i]);
                // }
            }
            createLrcObj(value)
            state.currentSongLyric = oLRC.ms
            // console.log('state.currentSongLyric', state.currentSongLyric)
        },
        ISPLAYMUSIC(state, value) {
            state.isplay = !value
        },
        SELECTSONGBYID(state, value) {
            state.currentID = value.id
            state.currentSong = value.list
            //保存原始列表
            state.isplay = true
        },
        //进入全屏模式
        GOTONOMAL(state, value) {
            state.fullScreen = value
        },
        CHANGEPLAYMODE(state) {
            mode = mode + 1
            state.mode = mode % 3
        },
    },
    state: {
        //查询的歌曲列表
        songList: [],
        //歌单列表
        songListMean:[],
        //播放的歌曲列表 --历史记录
        playList: [],
        //顺序歌曲列表
        sequencePlayList: [],
        //去重列表
        sequencePlayListJust: [],
        //播放模式
        mode: playMode.sequence, //默认顺序播放
        //当前播放歌曲在用户列表中的下标
        currentID: null,
        //当前的要播放的歌曲信息
        currentSong: {},
        //当前歌曲是否在播放
        isplay: false,
        //是否要进入全屏播放
        fullScreen: false,
        //当前歌曲的歌词
        currentSongLyric: []
    },
    getters: {
        //播放歌曲列表根据原始列表和mode得到的
        playList(state) {

            if (state.mode === playMode.sequence) {
                return [...state.sequencePlayListJust]
            }
            else if (state.mode === playMode.loop) {
                return [...state.sequencePlayListJust]
            }
            else if (state.mode === playMode.random) {
                // console.log('随机播放啦')
                //对原始歌曲列表复制
                const newArr = [...state.sequencePlayListJust]
                for (let i = 0; i < newArr.length; i++) {
                    const item = newArr[i]
                    const randomIndex = Math.floor(Math.random() * (i + 1))
                    //i=0时，randomIndex的值只有可能为  0
                    //i=1时，randomIndex的值只有可能为  0 1
                    //i=2时，randomIndex的值只有可能为  0 1 2
                    //             .....                  //
                    //radomIndex值就是遍历出来的随机位置
                    newArr[i] = newArr[randomIndex]; //第i个值和randomIndex对换
                    //进行打乱原始歌曲列表
                    newArr[randomIndex] = item;
                }
                 console.log(newArr)
                //设置播放的歌曲列表
                return newArr
            }
        },
    },
}

//暴露configure
export default song